package com.tenglong.teacher.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tenglong.teacher.R;

/**
 * @author hdx on 2019/2/26.
 */
public class UpdateVersionDialog implements View.OnClickListener {
    private final ProgressBar mProgressBar;
    private TextView mSchedule;
    private View mView;
    private Dialog mDialog;
    private Context context;

    public UpdateVersionDialog(Context context) {
        this.context = context;
        mView = LayoutInflater.from(context).inflate(R.layout.update_version_dialog, null);
        mProgressBar = mView.findViewById(R.id.mProgressBar);
        mSchedule = mView.findViewById(R.id.mSchedule);
        mView.findViewById(R.id.mHiddenWindow).setOnClickListener(this);
        mView.findViewById(R.id.mClose).setOnClickListener(this);
    }

    public void showDialog() {
        if (mDialog == null) {
            mDialog = new Dialog(context);
            mDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            mDialog.addContentView(mView, new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.WRAP_CONTENT));
        }
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
    }

    @SuppressLint("NewApi")
    public void closeDialog() {
        if(mDialog != null) {
            if(mDialog.isShowing()) { //check if dialog is showing.

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper)mDialog.getContext()).getBaseContext();

                //if the Context used here was an activity AND it hasn't been finished or destroyed
                //then dismiss it
                if(context instanceof Activity) {
                    if(!((Activity)context).isFinishing() && !((Activity)context).isDestroyed())
                        mDialog.dismiss();
                } else //if the Context used wasnt an Activity, then dismiss it too
                    mDialog.dismiss();
            }
            mDialog = null;
        }
    }

    public void updateProgressBar(int plan) {
        mProgressBar.setProgress(plan);
        mSchedule.setText(plan + "%");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mHiddenWindow:
                /**
                 * 隐藏窗口
                 */
                closeDialog();
                break;
            case R.id.mClose:
                closeDialog();
                break;
        }
    }
}
